<%@ include file="/common/common.jsp"%>
<%@ page language="java" pageEncoding="UTF-8"%>
<head>
<!--添加弹层效果和layui-->
<script type="text/javascript" src="<%=jsPath%>/layer/layer.js"></script>
<!-- <link rel="stylesheet" type="text/css" href="<%=jsPath%>/ztree/css/demo.css" /> -->
<!-- <link rel="stylesheet" type="text/css" href="<%=jsPath%>/ztree/css/zTreeStyle/zTreeStyle.css" /> -->
<link rel="stylesheet" type="text/css" href="<%=jsPath%>/ztree/css/metroStyle/metroStyle.css" />
<script type="text/javascript" src="<%=jsPath%>/ztree/jquery.ztree.all.js"></script>
<script type="text/javascript" src="<%=jsPath%>/ztree/jquery.ztree.exhide.js"></script>
<!-- <script type="text/javascript" src="<%=jsPath%>/ztree/jquery.ztree.excheck.js"></script> -->

<style>
    .offlinecar_ico_open{
		width: 16px !important;
		height: 16px !important;margin-right:2px !important;
		background-image:url('<%=ApplicationPath%>/image/videooff-offline.png')  !important ;
	}
    .offlinecar_ico_close{
		width: 16px !important;
		height: 16px !important;margin-right:2px !important;
		background-image:url('<%=ApplicationPath%>/image/videooff-offline.png')  !important ;
	}
    .department_ico_open{
		width: 16px !important;
		height: 16px !important;margin-right:2px !important;
		background-image:url('<%=ApplicationPath%>/image/videooff-offline.png')  !important ;
	}
    .department_ico_close{
		width: 16px !important;
		height: 16px !important;margin-right:2px !important;
		background-image:url('<%=ApplicationPath%>/image/videooff-offline.png')  !important ;
	}
    .zTreeDemoBackground2 {
        width:300px;
        height:100%;
        background-color:rgb(217, 229, 252);
        text-align:left;
        overflow-x: scroll;
        overflow-y: auto;
        }
    .publicDiv{
        position: relative;
        margin-top: 5px;
        margin-left: 10px;
        width:100%;
        height:60px;
        color:red;
        /* overflow: auto; */
        border: 1px solid rgb(54, 137, 247);
    }
    .videoChannelsDataDiv{
        position:relative;
        margin-top: 15px;
        margin-left: 10px;
        width:100%;
        height:60px;
        /* overflow: auto; */
        border: 1px solid rgb(54, 137, 247);
    }
    .transmitDiv{
        position:relative;
        margin-top: 15px;
        margin-left: 10px;
        width:100%;
        height:60px;
        /* overflow: auto; */
        border: 1px solid rgb(54, 137, 247);
    }

</style>
<script>

    /*
    功能描述：
        1.批量设置车辆默认的视频通道
        2.批量设置需要转发的车辆信息
    
    功能架构和流程

        1.公用功能
            1.显示车辆信息
    `
        1.批量设置车辆默认视频通道
            1.1获取车辆信息，并且格式化
            1.2获取车辆视频通道保存数据
            1.3获取车辆终端型号信息

    */

    //////////////////////////////////////////////////////////////////////////////////
    ////定义调试输出方法
    var flg = true;
    var outDebugInfo = function(msg){
        if(flg){
            console.log(msg);
        }
    }

    //////////////////////////////////////////////////////////////////////////////////公共方法
    var treeManager = null;//定义车辆树管理对象
    var treeNodes = {};//定义车辆节点对象
    var channelMaxIndex = 25;//定义通道号最大值
    var addVehicleIdsData = [];//定义保存添加的车辆信息
    var saveFlg_Save = "save";//定义保存标记为保存
    var saveFlg_add = "add";//定义保存标记为添加

    var vehicelNum = 0;//定义车辆总数，用于保存车辆树中的车辆数量
    var vehicleChannelsNum = 16;//定义车辆视频通道总数，用于弹出层调用
    var vehicleChannelsDataStr = "";//定义车辆视频通道保存字符串，用于弹出层调用，

    //获取数据方法
    var getTreeNodes = function(callbackFlg){
        var url = "<%=ApplicationPath%>/vehicle/getVechecileTree.action";
        var filterParams = {};
        filterParams.updateNode = false;
        $.ajax({
            type: "POST",
            url: url,
            data:filterParams,
            success:function(data){
                // outDebugInfo("查询车辆信息");
                // outDebugInfo(data);
                treeNodes = data.treeData;
                checkVehicleData(treeNodes);//开始校验信息
                $.fn.zTree.init($("#treeDemo"), setting, treeNodes);
                treeManager = $.fn.zTree.getZTreeObj("treeDemo");
                
                if(callbackFlg == 0){
                    showAllVehicles();//显示所有
                }
                if(callbackFlg == 1){
                    getChannelsBasicData();//获取通道数据基本信息
                }
                if(callbackFlg == 2){
                    //获取转发车辆基本信息
                    getAllTransmitDatas();
                }
            },
        });
    }
    
    /*
    校验数据
        校验车辆树中的数据
        删除图标信息
        统计车辆数量和组织数量
    */
    var checkVehicleData = function(nodes){
        outDebugInfo("开始校验并格式化数据");
        // var nodes = treeManager.getNodes();
        // outDebugInfo(nodes);
        formatTreeNodesData(nodes);
        // outDebugInfo("当前车辆树中车辆总数为 ： "+vehicelNum);
    }

    
    //格式化节点数据
    var formatTreeNodesData = function(nodes){
        if(nodes.length > 0){
            $.each(nodes,function(i,node){
                //删除图标信息
                delete node.iconSkin;

                //统计车辆数
                if(node.id.indexOf("v") >= 0){
                    vehicelNum ++;
                }

                //删除车辆通道信息
                if(node.id.indexOf("v") >= 0){
                    node.children = null;
                }


                if(node.id.indexOf("d") >= 0){
                    //遍历处理
                    var childrens = node.children;
                    if(!Utility.isUndefined(childrens)){
                        formatTreeNodesData(childrens);
                    }
                }
            });

        }
    }





    //显示所有车辆
    var showAllVehicles = function(){
        $.fn.zTree.init($("#treeDemo"), setting, treeNodes);
        openRoot();//展开根节点
    }
    //展开根节点   
    var openRoot = function(){
        if(treeManager != null){
            var nodes = treeManager.getNodes();
            // console.log(nodes);
            treeManager.expandNode(nodes[0],true,false,true,false);
        }
    }
    
    //车辆树单击事件回调方法，要写在setting前
	var onTreeClick = function(event, treeId, treeNode, clickFlag){
        console.log("单击事件");
        // console.log(event);
        // console.log(treeId);
        console.log(treeNode);
        // console.log(clickFlag);
        if(treeNode.id.indexOf("ch") >= 0){
            if(treeNode.value != ""){
                $("#channelsData_a").html(treeNode.value);
            }
        }
    }
    
    //获取设置的字体信息,写在setting前
    var  getFont = function(treeId, node) {
			return node.font ? node.font : {};
		}
    
    //ztree的设定
    var setting = {
            check: {
                enable: true
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {
				onClick: onTreeClick,
			},
            view: {
                nameIsHTML:true,
                showIcon: false,
                fontCss: getFont,
            },
            
        };



    $(document).ready(function(){
        getTreeNodes(0);
    });

    var showMsg = function(msg){
        $("#infoMsg").html(msg);
        if(msg != ""){
            var timerName = 'timer'+Math.random*1000+1000;
            $(document).oneTime("3s",timerName,function(){
                $("#infoMsg").html("");
            });
        }
    }

    //查询车牌号
    var selectPlateNo = function(){
        outDebugInfo("查询车牌号");
        var plateNoTemp = $("#plateNoText").val() + "&nbsp;&nbsp;&nbsp;"; 
        var node = treeManager.getNodeByParam("name",plateNoTemp,null);
        if(node != null){
            $.fn.zTree.init($("#treeDemo"), setting, node);
        }else{
            showMsg("没有查询到当前车牌号");
            showAllVehicles();
        }
    }


    //获取选中的车辆信息
    var getCheckedVehiclesData = function(vehicleIds,channelsDataStr){

        var flg = 0;//如果没有获取到车牌号，空值加1
        // addVehicleIdsData=[];//清空添加对象
        // var vehicleIds = [];

        if(treeManager != null){
            var nodes = treeManager.getCheckedNodes(true);
            if(nodes && nodes.length >= 0){
                $.each(nodes,function(i,node){
                    var idTemp = '' + node.id;
                    if(idTemp.indexOf("v") >= 0){
                        var vehicleIdTemp = parseInt(idTemp.substring(1));
                        if(!isNaN(vehicleIdTemp)){
                            var plateNo  = "";
                            if(!node.attributes || !node.attributes.plateNo){
                                flg ++;
                            }else{
                                plateNo = node.attributes.plateNo;
                            }
                            var obj = {
                                vehicleId:vehicleIdTemp,
                                simNo:node.simNo,
                                plateNo:plateNo,
                                channelsDataStr:channelsDataStr,
                            };
                            vehicleIds.push(obj);
                        }
                    }
                });
                if (flg == 0) {
                    return true;
                }
            }
            // outDebugInfo(nodes);
        }
        return false;
    }

    ///////////////////////////////////////////////////////////////////////////////编辑车辆视频通道数据方法

    //设置单个节点的视频通道信息
    var showOneNodeChannelsData = function (node, data, colorFont,childrenFlg) {

        var font = colorFont;

        //设置颜色显示
        node.children = null;
        node.font = font;
        var parentNode = treeManager.getNodeByParam("id", node.pid, null);
        if (parentNode != null) {
            parentNode.font = font;
        }

        if(childrenFlg){
            var id = "ch" + data.vehicleId;
            var name = "默认通道：";
            var value = data.channelsDataStr;
            var simNo = data.simNo;
            var plateNo = data.plateNo;
            var pid = node.id;



            var nodeTemp = [{
                id: id,
                name: (name + value),
                pid: pid,
                value: value,
                simNo: simNo,
                plateNo: plateNo,
                font: font,
            }];
            // outDebugInfo(nodeTemp);
            node.children = nodeTemp;//设置子节点
        }

        
    }


    //从服务器获取基本的设置信息
    var getChannelsBasicData = function () {
        if (treeManager != null) {
            // var node = treeManager.getNodeByParam("simNo",40024859183,null);
            // $.fn.zTree.init($("#treeDemo"), setting, node);
            // treeManager = $.fn.zTree.getZTreeObj("treeDemo");
            outDebugInfo("开始设置通道信息");
            getAllTerminalData();
        }
    }
    
    //获取车辆终端型号信息
    var getAllTerminalData = function(){
        if(treeManager == null){
            return ;
        }
        var url = "<%=ApplicationPath%>/vehicleRealTimeVideo/getAllTerminalData.action";
        var param = {};
        Utility.getAjaxData(url,JSON.stringify(param),function(data){
            console.log("获取所有车辆终端类型信息成功");
            // console.log(data);
            if(data.success){
                var dataTemp = data.data;
                if(dataTemp && dataTemp.length > 0){
                    $.each(dataTemp,function(i,temp){
                        //开始加载通道信息
                        var node = treeManager.getNodeByParam("simNo",temp.simNo,null);
                        if(node != null){
                            node.termType = temp.termType;
                            var termTypeTemp = ''+temp.termType;
                            var index = node.name.indexOf("&");
                            if(index > 0){
                                node.name = node.name.substring(0,index) + "&nbsp;&nbsp;&nbsp;" + termTypeTemp;
                            }else{
                                node.name += "&nbsp;&nbsp;" + termTypeTemp;
                            }
                            // node.name += "&nbsp;&nbsp;" + termTypeTemp;
                            // node.name = temp.attributes.plateNo + "&nbsp;&nbsp;" + termTypeTemp;
                        }
                        
                    });
                    var nodesTemp = treeManager.getNodes();//获取所有节点
                    // outDebugInfo(nodesTemp);
                    treeNodes = nodesTemp;
                    showAllVehicles();
                }

                getAllChannelsData();
            }
        });
    }
    
    /*
    获取所有车辆的视频通道保存数据
    */
    var getAllChannelsData = function(){
        if(treeManager == null){
            return ;
        }
        var url = "<%=ApplicationPath%>/vehicleRealTimeVideo/getAllChannelsDataStr.action";
        var param = {};
        Utility.getAjaxData(url,JSON.stringify(param),function(data){
            console.log("获取所有车辆视频通道信息成功");
            // console.log(data);
            if(data.success){
                var dataTemp = data.data;
                if(dataTemp && dataTemp.length > 0){
                    var font = { 'color': 'blue' };
                    $.each(dataTemp,function(i,temp){
                        //开始加载通道信息
                        var node = treeManager.getNodeByParam("simNo",temp.simNo,null);
                        if(node != null){
                            node.saveFlg = saveFlg_Save;
                            showOneNodeChannelsData(node,temp,font,true);
                        }
                        
                    });
                    var nodesTemp = treeManager.getNodes();//获取所有节点
                    // outDebugInfo(nodesTemp);
                    treeNodes = nodesTemp;
                    showAllVehicles();
                    showMsg("获取视频通道相关信息成功");
                }
            }
        });
    }
    
    

    //设置编辑按钮事件
    var setChannelsData = function(){
        // var channelsDataStrTemp = $("#channelsDataStrText").val();
        var channelsDataStrTemp = $("#channelsData_a").html();
        if(!checkedChannelsData(channelsDataStrTemp)){
            showMsg("设置默认视频通道格式不正确");
            return;
        }
        // var flg = 0;//如果没有获取到车牌号，空值加1
        addVehicleIdsData=[];//清空添加对象
        var vehicleIds = [];
        var flg = getCheckedVehiclesData(vehicleIds,channelsDataStrTemp);
        //获取车辆信息正确
        if(flg){
            outDebugInfo("格式化需要添加的数据完成!");
            addVehicleIdsData = vehicleIds;
            showChangedDatas(vehicleIds,true);
            outDebugInfo(treeNodes);
            if(vehicleIds.length > 0){
                saveChannelsData(vehicleIds);
            }else{
                showMsg("请选择需要设置的车辆");
            }
        }

        // outDebugInfo(vehicleIds);
    }
    
    //校验视频通道数据格式
    var checkedChannelsData = function (str) {
        // outDebugInfo("开始校验通道数据");
        var flg = false;
        var channelsTemp = str.split(",");
        outDebugInfo(channelsTemp);
        if (channelsTemp.length > 0) {
            var num = 0;
            $.each(channelsTemp, function (i, channel) {
                var temp = parseInt(channel);
                // outDebugInfo(temp);
                if (!isNaN(temp) && ('' + temp) == channel) {
                    if (temp > 0 && temp < channelMaxIndex) {
                        num++;
                    }
                }
            });
            if (num == channelsTemp.length) {
                flg = true;
            }
        }

        return flg;
    }
    
    //设置显示新的修改信息
    var showChangedDatas = function(datas,childrenFlg){
        if(!datas || datas.length <= 0){
            return ;
        }
        var font = { 'color': 'red' };
        $.each(datas,function(i,data){
            var node = treeManager.getNodeByParam("simNo", data.simNo, null);
            if (node != null) {
                // node.saveFlg = saveFlg_add;
                showOneNodeChannelsData(node, data, font,childrenFlg);
            }
        });
        var nodesTemp = treeManager.getNodes();//获取所有节点
        // outDebugInfo(nodesTemp);
        treeNodes = nodesTemp;
        showAllVehicles();
    }

    

    //显示编辑车辆视频通道数据教程
    var showVehicelChannelsDataCourse = function(){
        var url = "<%=ApplicationPath%>/course/editVehicleChannelsDataCourse.html";
        InfoWindow.open(url,600,450,"修改视频通道教程");
    }

    //显示通道编辑页面
    var showChannelsEditPage = function(){
        vehicleChannelsDataStr = $("#channelsData_a").html();
        outDebugInfo("开始选择通道编辑页面");
        layer.open({
            title: '选择视频通道',
            type: 2,
            area: ['480px', '260px'],
            fixed: false, //不固定
            // offset:['150px','450px'],
            maxmin: false,
            content: '<%=ApplicationPath%>/vehicleRealTimeVideo/editDefaultChannels.action',
            cancel: function () {
                // layer.msg('没有进行任何操作就关闭');
            }
        });
    }

    //保存通道数据信息字符串，由弹出层调用
    var saveChannelsDataStr = function(str){
        $("#channelsData_a").html(str);
    }
    
    //保存通道数据
    var saveChannelsData  = function(vehicleIds){
        if(treeManager == null){
            return;
        }
        if(vehicleIds && vehicleIds.length > 0){
            var urlInsert = "<%=ApplicationPath%>/vehicleRealTimeVideo/insertChannelDataStr.action";
            var urlUpdate = "<%=ApplicationPath%>/vehicleRealTimeVideo/updateChannelDataStr.action";
            var url = "";
            var info = "";
            var saveDataFlg = true;
            var errorMsg = "";
            $.each(vehicleIds,function(i,data){
                var node = treeManager.getNodeByParam("simNo",data.simNo,null);
                if(node){
                    if(node.saveFlg == saveFlg_Save){
                        url = urlUpdate;
                        info = "更新";
                    } else {
                        url = urlInsert;
                        info = "插入";
                    }
                    Utility.getAjaxData(url, JSON.stringify(data), function (result) {
                        if(result.success){
                            outDebugInfo(info + data.plateNo + "通道数据成功");
                            node.saveFlg = saveFlg_Save;
                        }else{
                            saveDataFlg = false;
                            outDebugInfo(info + data.plateNo + "通道数据失败 ："+result.message);
                            errorMsg += result.message;
                        }
                    });
                }
            });
            if(saveDataFlg){
                showMsg("更新数据成功，5s后自动刷新");
                $(document).oneTime("5s","refreshAddVehicleTree",function(){
                    getChannelsBasicData();//重新获取基本信息
                    showMsg("刷新数据完成");
                });
            }else{
                showMsg("更新数据库发生错误 : " + errorMsg);
            }
            
        }
    }


    
    ///////////////////////////////////////////////////////////////////////////////设置车辆转发方法

    /*
    1.获取数据库中的转发车辆信息，并显示到车辆树上
    2.点击设置按钮，添加选中的车辆到数据库
    */

    var getAllTransmitDatas = function(){
        outDebugInfo("获取转发车辆信息");
        if(treeManager == null){
            return ;
        }
        var url = "<%=ApplicationPath%>/vehicleRealTimeVideo/getAllTransmitData.action";
        var param = {};
        Utility.getAjaxData(url,JSON.stringify(param),function(data){
            console.log("获取所有转发车辆信息成功");
            console.log(data);
            if(data.success){
                var dataTemp = data.data;
                if(dataTemp && dataTemp.length > 0){
                    var font = { 'color': 'blue' };
                    $.each(dataTemp,function(i,temp){
                        //开始加载通道信息
                        var node = treeManager.getNodeByParam("simNo", temp.simNo, null);
                        if (node != null) {
                            node.saveFlg = saveFlg_Save;

                            showOneNodeChannelsData(node,null,font,false);
                            // node.font = font;
                            // var parentNode = treeManager.getNodeByParam("id", node.pid, null);
                            // if (parentNode != null) {
                            //     parentNode.font = font;
                            // }
                        }    
                    });
                    var nodesTemp = treeManager.getNodes();//获取所有节点
                    // outDebugInfo(nodesTemp);
                    treeNodes = nodesTemp;
                    showAllVehicles();
                    showMsg("获取转发车辆信息成功");
                }
            }
        });
    }

    //添加转发车辆
    var addTransmitVehicles = function(){
        var vehicleDatas = [];
        getCheckedVehiclesData(vehicleDatas,"");//获取添加数据
        showChangedDatas(vehicleDatas,false);
        saveTramsmitDatas(vehicleDatas);//保存数据
        outDebugInfo(vehicleDatas);
    }

     //保存转发车辆数据
     var saveTramsmitDatas  = function(vehicleIds){
        if(treeManager == null){
            return;
        }
        var me = this;
        var font = { 'color': 'red' };
        
        if(vehicleIds && vehicleIds.length > 0){
            var urlInsert = "<%=ApplicationPath%>/vehicleRealTimeVideo/insertTransmitData.action";
            var saveDataFlg = true;
            var savedNum = 0;
            var errorMsg = "";
            var showResultMsg = function () {

                outDebugInfo("显示结果信息")
                if (saveDataFlg) {
                    showMsg("更新数据成功，5s后自动刷新");
                    $(document).oneTime("5s", "refreshAddVehicleTree", function () {
                        getAllTransmitDatas();//重新获取基本信息
                    });
                } else {
                    showMsg("更新数据库发生错误 : " + errorMsg);
                }
            }
            $.each(vehicleIds,function(i,data){
                var node = treeManager.getNodeByParam("simNo",data.simNo,null);
                if(node != null) {
                    //只插入不更新
                    if (node.saveFlg != saveFlg_Save) {

                        // outDebugInfo("node.saveFlg = " + node.saveFlg);
                        Utility.getAjaxData(urlInsert, JSON.stringify(data), function (result) {
                            // outDebugInfo(result);
                            if (result.success) {
                                outDebugInfo("插入" + data.plateNo + "通道转发车辆成功");
                                node.saveFlg = saveFlg_Save;
                            } else {
                                outDebugInfo("插入" + data.plateNo + "通道转发车辆失败 ：" + result.message);
                                errorMsg += result.message;
                                saveDataFlg = false;
                            }
                            savedNum ++;//计数
                            //接收到最后一个信息后
                            if(savedNum == vehicleIds.length){
                                showResultMsg();
                            }
                        });
                    }
                }
            });
            

            
            
        }
    }

    
    

</script>
</head>
<body>
    <div class="zTreeDemoBackground2">
        <ul id="treeDemo" class="ztree"></ul>
    </div>
    <div style="position:absolute;top:5px;left:310px;width:900px;height:100%;">
        <div class="publicDiv">
            <span>提示信息 ：</span>
        <span id="infoMsg"></span>
        <br/><br/>
        <span>车牌号：
            <input id="plateNoText" type="text" width="150px;"/>
            <input type="button" value="查 询 车 牌 号" onclick="javascript:selectPlateNo();"/>
            <input type="button" value="显示所有车辆" onclick="javascript:getTreeNodes(0);" />    
        </span>
        <span>
                &nbsp;&nbsp;<a href="javascript:void(0);" onclick="javascript:showVehicelChannelsDataCourse();">教程</a>
        </span>
        </div>
        <div class="videoChannelsDataDiv">
            
            <span>&nbsp;&nbsp;&nbsp;&nbsp;设置视频通道功能 : </span>
            &nbsp;&nbsp;&nbsp;&nbsp;
            <input type="button" value="首先获取视频通道相关信息" onclick="javascript:getTreeNodes(1);"/>
            <br />
            <span> &nbsp;&nbsp;&nbsp;&nbsp;需要设置的默认通道号(例："1,3,5")：
                <!-- <input id="channelsDataStrText" type="text"  style="width:150px;" onclick="javascript:showChannelsEditPage();"/> -->
                <span>
                    &nbsp;&nbsp;
                    <a id="channelsData_a" href = "javascript:void(0);" onclick="javascript:showChannelsEditPage();">点我设置</a>
                    &nbsp;&nbsp;
                </span>
                <input type="button" value="设 置 默 认 通 道 号" onclick="javascript:setChannelsData();"/>
            </span>
            
        </div>
        <div class="transmitDiv">
            <span>&nbsp;&nbsp;&nbsp;&nbsp;设置车辆转发功能 : </span>
            &nbsp;&nbsp;&nbsp;&nbsp;
            <input type="button" value="首先获取所有转发车辆的信息" onclick="javascript:getTreeNodes(2);"/>
            &nbsp;&nbsp;&nbsp;&nbsp;
            <input type="button" value="添加车辆信息" onclick="javascript:addTransmitVehicles();"/>
        </div>
    </div>
    
</body>